'''
Created on Mar 23, 2013

@author: Petko
'''
from django.views.generic.base import View
from sent.utils import createValidToken, CommonResult, ErrorIds, AccessToken
from sent.utils.result_printer import getPrinter
from sent.model.OpinionDBManager import OpinionDBManager
from uuid import UUID

class AddOpinions(View):
    '''
    classdocs
    '''
    
    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def post(self, *args, **kwargs):
        accessTokenStr = self.request.POST.get('access_token', None)
        viewId = self.request.POST.get('view_id', None)
        opinionIds = self.request.POST.get('opinion_ids', None)
        
        cResult = CommonResult()
        
        if accessTokenStr and viewId and opinionIds:
            
            accessToken, error = createValidToken(accessTokenStr)
            if accessToken:
                assert isinstance(accessToken, AccessToken)
                
                dbMan = OpinionDBManager(False)
                try:
                    view = dbMan.getViewById(viewId)
                    if view:
                        if accessToken.containsScope('view_adm') \
                            or (accessToken.containsScope(viewId + ':m')) \
                            or (view.containsDefaultScope('m') and accessToken.containsScope('all:m')):
                            
                            opinionIdsList = opinionIds.split(' ')
                            binOpinionIdsList = [UUID(opIdStr).bytes for opIdStr in opinionIdsList]
                            addedOpinionIds = dbMan.addOpinionsToView(view, binOpinionIdsList)
                            cResult.errorId = ErrorIds.SUCCESS
                            cResult.result = [str(UUID(bytes=opId)) for opId in addedOpinionIds]
                            dbMan.commitSession()
                        else:
                            cResult.errorId = ErrorIds.UNAUTHORIZED
                            cResult.result = "You don't have permission to modify this view"
                    else:
                        cResult.errorId = ErrorIds.NOT_FOUND
                        cResult.result = "View %s not found" % viewId
                        dbMan.rollbackSession()
                except:
                    dbMan.rollbackSession()
                    raise
            else:
                cResult.errorId = ErrorIds.UNAUTHORIZED
                cResult.result = error
        else:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = "Missing parameter"
            
        return getPrinter().printResult(cResult)
    
    